//
//  QKHttpManager.m
//  SmartTeaching
//
//  Created by yangqingluo on 15/9/6.
//  Copyright (c) 2015年 yangqingluo. All rights reserved.
//

#import "QKHttpManager.h"
#import "AppPublic.h"



#define kImageDataKey  @"image_data_7kers"
#define kFileKey @"image_file_7ker"
#define kNameKey @"image_name_7kers"


static char encodingTable[64] = {
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' };

@implementation NSData (SVHTTPRequest)

- (NSString *)base64EncodingWithLineLength:(unsigned int) lineLength {
    const unsigned char	*bytes = [self bytes];
    NSMutableString *result = [NSMutableString stringWithCapacity:[self length]];
    unsigned long ixtext = 0;
    unsigned long lentext = [self length];
    long ctremaining = 0;
    unsigned char inbuf[3], outbuf[4];
    short i = 0;
    unsigned int charsonline = 0;
    short ctcopy = 0;
    unsigned long ix = 0;
    
    while( YES ) {
        ctremaining = lentext - ixtext;
        if( ctremaining <= 0 ) break;
        
        for( i = 0; i < 3; i++ ) {
            ix = ixtext + i;
            if( ix < lentext ) inbuf[i] = bytes[ix];
            else inbuf [i] = 0;
        }
        
        outbuf [0] = (inbuf [0] & 0xFC) >> 2;
        outbuf [1] = ((inbuf [0] & 0x03) << 4) | ((inbuf [1] & 0xF0) >> 4);
        outbuf [2] = ((inbuf [1] & 0x0F) << 2) | ((inbuf [2] & 0xC0) >> 6);
        outbuf [3] = inbuf [2] & 0x3F;
        ctcopy = 4;
        
        switch( ctremaining ) {
            case 1:
                ctcopy = 2;
                break;
            case 2:
                ctcopy = 3;
                break;
        }
        
        for( i = 0; i < ctcopy; i++ )
            [result appendFormat:@"%c", encodingTable[outbuf[i]]];
        
        for( i = ctcopy; i < 4; i++ )
            [result appendFormat:@"%c",'='];
        
        ixtext += 3;
        charsonline += 4;
    }
    
    return result;
}

- (BOOL)isJPG {
    if (self.length > 4) {
        unsigned char buffer[4];
        [self getBytes:&buffer length:4];
        
        return buffer[0]==0xff &&
        buffer[1]==0xd8 &&
        buffer[2]==0xff &&
        buffer[3]==0xe0;
    }
    
    return NO;
}

- (BOOL)isPNG {
    if (self.length > 4) {
        unsigned char buffer[4];
        [self getBytes:&buffer length:4];
        
        return buffer[0]==0x89 &&
        buffer[1]==0x50 &&
        buffer[2]==0x4e &&
        buffer[3]==0x47;
    }
    
    return NO;
}

- (BOOL)isGIF {
    if(self.length >3) {
        unsigned char buffer[4];
        [self getBytes:&buffer length:4];
        
        return buffer[0]==0x47 &&
        buffer[1]==0x49 &&
        buffer[2]==0x46; //Signature ASCII 'G','I','F'
    }
    return  NO;
}

- (NSString *)getImageType {
    NSString *ret;
    if([self isJPG]) {
        ret=@"jpg";
    }
    else if([self isGIF]) {
        ret=@"gif";
    }
    else if([self isPNG]) {
        ret=@"png";
    }
    else {
        ret=nil;
    }
    return ret;
}

@end


__strong static QKHttpManager  *_singleManager = nil;

@implementation QKHttpManager

+(QKHttpManager *) sharedManager{
    static dispatch_once_t pred = 0;
    
    dispatch_once(&pred, ^{
        _singleManager = [[QKHttpManager alloc]init];
    });
    return _singleManager;
}

-(instancetype)init{
    if (_singleManager) {
        return _singleManager;
    }
    
    self = [super init];
    
    if (self) {
        
    }
    
    return self;
}

NSString *stringFromOrderType(OrderType type){
    switch (type) {
        case OrderTypeAll:{
            return @"所有";
        }
            break;
            
        case OrderTypeNotPay:{
            return @"等待付款";
        }
            break;
            
        case OrderTypeWaiting:{
            return @"等待发货";
        }
            break;
            
        case OrderTypeSended:{
            return @"已经发货";
        }
            break;
            
        case OrderTypeDone:{
            return @"已完成";
        }
            break;
            
        default:{
            return @"未知状态";
        }
            break;
    }
}

UIColor *colorFromOrderType(OrderType type){
    switch (type) {
        case OrderTypeNotPay:{
            return [UIColor orangeColor];
        }
            break;
            
        case OrderTypeSended:{
            return [UIColor blackColor];
        }
            break;
            
        default:{
            return [UIColor lightGrayColor];
        }
            break;
    }
}


NSString *generateUuidString(){
    // create a new UUID which you own
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    
    // create a new CFStringRef (toll-free bridged to NSString)
    // that you own
    NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
    
    
    // release the UUID
    CFRelease(uuid);
    
    return uuidString;
}

NSString *DataToJsonString(id object){
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

+ (NSString*)parameterStringForDictionary:(NSDictionary*)parameters {
    NSMutableArray *stringParameters = [NSMutableArray arrayWithCapacity:parameters.count];
    
    [parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if([obj isKindOfClass:[NSString class]]) {
            [stringParameters addObject:[NSString stringWithFormat:@"%@=%@", key, [self encodedURLParameterString:obj]]];
        }
        else if([obj isKindOfClass:[NSNumber class]]) {
            [stringParameters addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
        }
        else
            [NSException raise:NSInvalidArgumentException format:@"requests only accept NSString, NSNumber and NSData parameters."];
    }];
    
    return [stringParameters componentsJoinedByString:@"&"];
}

+ (NSString*)encodedURLParameterString:(NSString *)string {
    NSString *result = (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                            (__bridge CFStringRef)string,
                                                                                            NULL,
                                                                                            CFSTR(":/=,!$&'()*+;[]@#?^%\"`<>{}\\|~ "),
                                                                                            kCFStringEncodingUTF8);
    return result;
}

- (NSString*)parameterStringForDictionary:(NSDictionary*)parameters {
    NSMutableArray *stringParameters = [NSMutableArray arrayWithCapacity:parameters.count];
    
    [parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if([obj isKindOfClass:[NSString class]]) {
            [stringParameters addObject:[NSString stringWithFormat:@"%@=%@", key, [self encodedURLParameterString:obj]]];
        }
        else if([obj isKindOfClass:[NSNumber class]]) {
            [stringParameters addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
        }
        else
            [NSException raise:NSInvalidArgumentException format:@"requests only accept NSString, NSNumber and NSData parameters."];
    }];
    
    return [stringParameters componentsJoinedByString:@"&"];
}

- (NSString*)encodedURLParameterString:(NSString *)string {
    NSString *result = (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                            (__bridge CFStringRef)string,
                                                                                            NULL,
                                                                                            CFSTR(":/=,!$&'()*+;[]@#?^%\"`<>{}\\|~ "),
                                                                                            kCFStringEncodingUTF8);
    return result;
}





+ (void)getWithURLString:(NSString *)urlString loginPermission:(BOOL)permission timeoutInterval:(NSTimeInterval)timeoutInterval completion:(NetworkFinishedFunc)completion{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError *error;
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlAddress,urlString]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeoutInterval];
        
        if (permission) {
            [request setValue:[NSString stringWithFormat:@"%@",[AppPublic shareInstanceApp].Token] forHTTPHeaderField:@"token"];
        }
        
        NSLog(@"%@",request.allHTTPHeaderFields);
        
        NSData * netData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                NSString *strReceive = [[NSString alloc] initWithData:netData encoding:NSUTF8StringEncoding];
                NSDictionary *dicReceive = [NSJSONSerialization JSONObjectWithData:[strReceive dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
                completion(dicReceive, error);
            }
            else{
                completion(nil,error);
            }
            
        });
        
    });
}

+ (void)deleteWithURLString:(NSString *)urlString loginPermission:(BOOL)permission timeoutInterval:(NSTimeInterval)timeoutInterval completion:(NetworkFinishedFunc)completion{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError *error;
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlAddress,urlString]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeoutInterval];
        [request setHTTPMethod:@"DELETE"];//设置请求方式为DELETE，默认为GET
        
//        if (permission) {
//            [request setValue:[NSString stringWithFormat:@" HAuth %@",[AppPublic shareInstanceApp].Token] forHTTPHeaderField:@"Authorization"];
//        }
        
        
        NSData * netData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                NSString *strReceive = [[NSString alloc] initWithData:netData encoding:NSUTF8StringEncoding];
                NSDictionary *dicReceive = [NSJSONSerialization JSONObjectWithData:[strReceive dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
                completion(dicReceive, error);
            }
            else{
                completion(nil,error);
            }
            
        });
        
    });
}

+ (void)postImageWithURLString:(NSString *)urlString NSArray:(NSArray *)imageArray timeoutInterval:(NSTimeInterval)timeoutInterval completion:(NetworkFinishedFunc)completion{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlAddress,urlString]];
        
        NSString *TWITTERFON_FORM_BOUNDARY = @"acebdf13572468";
        //根据url初始化request
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                           timeoutInterval:10];
        
        
        //分界线 --AaB03x
        NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
        //结束符 AaB03x--
        NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
        
        //声明myRequestData，用来放入http body
        NSMutableData *myRequestData=[NSMutableData data];
        
        for (NSDictionary *imageDic in imageArray) {
            //得到图片的data
            NSData* data = [imageDic objectForKey:kImageDataKey];
            
            //http body的字符串
            NSMutableString *body=[[NSMutableString alloc]init];
            
            
            ////添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            
            //声明pic字段
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",[imageDic objectForKey:kFileKey],[imageDic objectForKey:kNameKey]];
            //声明上传文件的格式
            [body appendFormat:@"Content-Type: image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg\r\n\r\n"];
            
            //将body字符串转化为UTF8格式的二进制
            [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
            
            [myRequestData appendData:data];
        }
        
        //声明结束符：--AaB03x--
        NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
        //加入结束符--AaB03x--
        [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
        
        //设置HTTPHeader中Content-Type的值
        NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
        //设置HTTPHeader
        [request setValue:content forHTTPHeaderField:@"Content-Type"];
        
//        [request setValue:[NSString stringWithFormat:@" HAuth %@",[AppPublic shareInstanceApp].Token] forHTTPHeaderField:@"Authorization"];
        
        //设置Content-Length
        [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
        //设置http body
        [request setHTTPBody:myRequestData];
        //http method
        [request setHTTPMethod:@"POST"];
        
//        [request setValue:@"Dalvik/1.6.0 (Linux; U; Android 4.4.2; NX503A Build/KVT49L)" forHTTPHeaderField:@"User-Agent"];
//        [request setValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];
//        [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
//        [request setValue:@"localhost:12345" forHTTPHeaderField:@"Host"];
        
        NSError *error;
        //连接服务器
        NSData *netData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *strReceive = [[NSString alloc] initWithData:netData encoding:NSUTF8StringEncoding];
            NSDictionary *dicReceive = [NSJSONSerialization JSONObjectWithData:[strReceive dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
            completion(dicReceive, error);
            
        });
        
    });
}





+ (void)postWithURLString:(NSString *)urlString loginPermission:(BOOL)permission dictionary:(NSDictionary *)dictionary timeoutInterval:(NSTimeInterval)timeoutInterval completion:(NetworkFinishedFunc)completion{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlAddress,urlString]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeoutInterval];
        [request setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
        
        if (permission) {
            [request setValue:[NSString stringWithFormat:@"%@",[AppPublic shareInstanceApp].Token] forHTTPHeaderField:@"token"];
        }
        
        if (dictionary) {
            const char *stringData = [[self parameterStringForDictionary:dictionary] UTF8String];
            NSMutableData *postData = [NSMutableData dataWithBytes:stringData length:strlen(stringData)];
            [request setHTTPBody:postData];
        }
        
        NSLog(@"%@",request.allHTTPHeaderFields);
        
        
        NSError *error;
        //连接服务器
        NSData *netData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
//                NSStringEncoding strEncode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
                NSString *strReceive = [[NSString alloc] initWithData:netData encoding:NSUTF8StringEncoding];
                NSDictionary *dicReceive = [NSJSONSerialization JSONObjectWithData:[strReceive dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
                completion(dicReceive, error);
            }
            else{
                completion(nil,error);
            }
            
        });
        
    });
}

+ (void)putWithURLString:(NSString *)urlString loginPermission:(BOOL)permission dictionary:(NSDictionary *)dictionary timeoutInterval:(NSTimeInterval)timeoutInterval completion:(NetworkFinishedFunc)completion{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlAddress,urlString]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeoutInterval];
        [request setHTTPMethod:@"PUT"];//设置请求方式为PUT，默认为GET
        request.HTTPShouldUsePipelining = YES;
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        
        if (permission) {
//            [request setValue:[NSString stringWithFormat:@" HAuth %@",[AppPublic shareInstanceApp].Token] forHTTPHeaderField:@"Authorization"];
            
            
//            NSString *authStr = [NSString stringWithFormat:@"%@:%@", [AppPublic shareInstanceApp].username, [AppPublic shareInstanceApp].password];
//            NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
//            NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:140]];
//            [request setValue:authValue forHTTPHeaderField:@"Authorization"];
        }
        
        const char *stringData = [[self parameterStringForDictionary:dictionary] UTF8String];
        NSMutableData *postData = [NSMutableData dataWithBytes:stringData length:strlen(stringData)];
        [request setHTTPBody:postData];
        
        NSError *error;
        //连接服务器
        NSData *netData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                //                NSStringEncoding strEncode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
                NSString *strReceive = [[NSString alloc] initWithData:netData encoding:NSUTF8StringEncoding];
                NSDictionary *dicReceive = [NSJSONSerialization JSONObjectWithData:[strReceive dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
                completion(dicReceive, error);
            }
            else{
                completion(nil,error);
            }
            
        });
        
    });
}


//登录
+ (void)loginWithUsername:(NSString *)username password:(NSString *)password completion:(NetworkFinishedFunc)completion{
     [self postWithURLString:@"anon/buyerLogin" loginPermission:NO dictionary:@{@"params":[NSString stringWithFormat:@"{\"phoneNum\":\"%@\",\"passWord\":\"%@\",}",username,password]} timeoutInterval:responseTime completion:^(NSObject *object, NSError *error)
    {
//#if DEBUG
//        //测试使用
//        error = nil;
//        object = @{@"code":@QKHTTP_SUCCESS};
//#endif
        
        
        //登录成功，记录登录数据
        if (!error) {
            if ([object isKindOfClass:[NSDictionary class]]) {
                if ([((NSDictionary *)object)[@"code"] intValue] == QKHTTP_SUCCESS) {
                    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
                    
                    [ud setObject:[NSString stringWithFormat:@"%@&%@",username,password] forKey:kUserName_Password];
                    
                    [ud synchronize];
                    
                    [AppPublic shareInstanceApp].Token = ((NSDictionary *)object)[@"token"];
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:kHttpStateLoginSuccess object:nil];
                }
            }
        }
        completion(object,error);
    }];
}

//获取手机验证码
+ (void)getIdentifyCodeWithPhone:(NSString *)phoneNum andIsRegistered:(BOOL)isRegistered completion:(NetworkFinishedFunc)completion{
    
    NSString *urlString = [NSString stringWithFormat:@"anon/getIdentifyCode?phoneNum=%@&isRegistered=%@",phoneNum, isRegistered ? @"true" : @"false"];
    
    [self getWithURLString:urlString loginPermission:NO timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        
        completion(object,error);
        
    }];
}

//注册
+ (void)registWithPhone:(NSString *)phoneNum password:(NSString *)password identifyCode:(NSString *)identifyCode andToken:(NSString *)token completion:(NetworkFinishedFunc)completion{
    [self postWithURLString:@"anon/buyerRegister" loginPermission:NO dictionary:@{@"params":[NSString stringWithFormat:@"{\"phoneNum\":\"%@\",\"passWord\":\"%@\",\"identifyCode\":\"%@\"}",phoneNum,password,identifyCode]} timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        
        completion(object,error);
    }];
}

//获取商品列表
+ (void)getProductsWithPage:(NSUInteger)pageNo type:(NSString *)type shopID:(NSString *)shopID categoryID:(NSString *)categoryID completion:(NetworkFinishedFunc)completion{
    if (!type || !shopID) {
        return;
    }
    NSString *paramsString = categoryID ? [NSString stringWithFormat:@"{\"pageNo\":\"%lu\",\"productType\":\"%@\",\"shopId\":\"%@\",\"categoryId\":\"%@\"}",(unsigned long)pageNo , type, shopID , categoryID] : [NSString stringWithFormat:@"{\"pageNo\":\"%lu\",\"productType\":\"%@\",\"shopId\":\"%@\"}",(unsigned long)pageNo , type, shopID];
    
    [self postWithURLString:@"anon/getSellerProducts" loginPermission:NO dictionary:@{@"params":paramsString} timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        

        
        
//#if DEBUG
//        //测试使用
//        error = nil;
//        
//        NSString *path=[[NSBundle mainBundle]pathForResource:@"products" ofType:@"json"];
//        NSData *data=[NSData dataWithContentsOfFile:path];
//        
//        object=[NSJSONSerialization JSONObjectWithData:data
//                                               options:NSJSONReadingAllowFragments
//                                                 error:nil];
//#endif
        completion(object,error);
    }];
}

//获取商品详情
+ (void)getProductWithProductID:(NSString *)productID couponType:(CouponType)type completion:(NetworkFinishedFunc)completion{
    if (!productID) {
        return;
    }
    
    [self postWithURLString:@"anon/getSellerProductDetail" loginPermission:NO dictionary:@{@"params":[NSString stringWithFormat:@"{\"productId\":\"%@\",\"couponType\":\"%d\"}",productID,type]} timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        
        completion(object,error);
    }];
}

//下订单
+ (void)checkOrdersWithAddress:(NSString *)addressId product:(UFShoppingProduct *)product invoice:(UFInvoice *)invoice completion:(NetworkFinishedFunc)completion{
    NSDictionary *productDic = @{@"productItemId":product.productItemId,@"quantity":[NSNumber numberWithInteger:product.quantity]};
    
//    NSDictionary *invoiceDic = @{@"title":invoice.title,@"type":invoice.type};
    
    NSDictionary *params = @{@"addressId":addressId,@"productInfo":productDic};
    
    [self postWithURLString:@"api/checkOrders" loginPermission:YES dictionary:@{@"params":DataToJsonString(params)} timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        
        completion(object,error);
    }];
}

//更新地址
+ (void)updateAddress:(UFAddressInfo *)addressInfo completion:(NetworkFinishedFunc)completion{
    NSMutableDictionary *params = [NSMutableDictionary new];
    
    if (addressInfo.idString) {
        [params setObject:addressInfo.idString forKey:@"addressId"];
    }
    [params setObject:addressInfo.name forKey:@"addressName"];
    [params setObject:addressInfo.deliveryName forKey:@"deliveryName"];
    [params setObject:addressInfo.deliveryPhone forKey:@"deliveryPhone"];
    [params setObject:addressInfo.detailAddress forKey:@"detailAddress"];
    [params setObject:addressInfo.def ? @"true" : @"false" forKey:@"isDefault"];
    
    [self postWithURLString:@"api/savaOrUpdateAddress" loginPermission:YES dictionary:@{@"params":DataToJsonString(params)} timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        
        completion(object,error);
    }];
}


//获取收货地址
+ (void)getAddressCompletion:(NetworkFinishedFunc)completion{
    [self postWithURLString:@"api/getBuyerAddressList" loginPermission:YES dictionary:nil timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        
        completion(object,error);
    }];
}

//获取默认收货地址
+ (void)getDefaultAddressCompletion:(NetworkFinishedFunc)completion{
    [self postWithURLString:@"api/getDefaultAddress" loginPermission:YES dictionary:nil timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        
        completion(object,error);
    }];
}

//获取订单列表
+ (void)getOrdersWithPage:(NSUInteger)pageNo type:(OrderType)type completion:(NetworkFinishedFunc)completion{
    NSString *paramsString = [NSString stringWithFormat:@"{pageNo:%lu,orderType:%d}",(unsigned long)pageNo , type];
    
    NSString *urlString = [NSString stringWithFormat:@"api/getBuyerOrderList?params=%@",[QKHttpManager encodedURLParameterString:paramsString]];
    
    [self getWithURLString:urlString loginPermission:YES timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        
        completion(object,error);
        
    }];
}

//删除收货地址
+ (void)deleteAddress:(NSString *)idString completion:(NetworkFinishedFunc)completion{
    NSDictionary *params = @{@"addressId":idString};
    
    [self postWithURLString:@"api/deleteBuyerAddress" loginPermission:YES dictionary:@{@"params":DataToJsonString(params)} timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        
        completion(object,error);
    }];
}

//支付订单
+ (void)payOrder:(NSString *)orderId paymentID:(NSString *)paymentId payStyleID:(NSString *)payID completion:(NetworkFinishedFunc)completion{
    NSDictionary *params;
    if (orderId) {
        params = @{@"orderId":orderId};
    }
    else if (paymentId){
        params = @{@"paymentId":paymentId};
    }
    
    
    if ([payID isEqualToString:@"001"]) {
        //支付宝支付
        [self postWithURLString:@"api/payment/alipay" loginPermission:YES dictionary:@{@"params":DataToJsonString(params)} timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
            
            completion(object,error);
        }];
    }
    else if ([payID isEqualToString:@"002"]) {
        //微信支付
        [self postWithURLString:@"api/payment/weixin/request" loginPermission:YES dictionary:@{@"params":DataToJsonString(params)} timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
            
            completion(object,error);
        }];
    }
}

//确认订单
+ (void)sureOrder:(NSString *)idString completion:(NetworkFinishedFunc)completion{
    NSDictionary *params = @{@"orderId":idString};
    
    [self postWithURLString:@"api/checkShipping" loginPermission:YES dictionary:@{@"params":DataToJsonString(params)} timeoutInterval:responseTime completion:^(NSObject *object, NSError *error){
        
        completion(object,error);
    }];
}

@end



